package com.jydw.da.frame.config.table;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.*;


/**
 * 多字段分片算法 按照数据库划分
 *
 * @author chenyj
 * @date 2023/06/27
 */

@Slf4j
public class MyComplexTableShardingAlgorithm implements ComplexKeysShardingAlgorithm<Long> {

    private static final String COLUMN1 = "id";

    private static final String COLUMN2 = "role_id";

    //可以从yml透传过来
    @Getter
    private Properties props;


    /**
     * 进行切分
     *
     * @param collection               数据库的逻辑表名称集合
     * @param complexKeysShardingValue 复合分片字段的字段名和字段值
     */
    @Override
    public Collection<String> doSharding(Collection<String> collection, ComplexKeysShardingValue<Long> complexKeysShardingValue) {
        String logicTableName = complexKeysShardingValue.getLogicTableName();
        Map<String, Collection<Long>> columnNameAndShardingValuesMap = complexKeysShardingValue.getColumnNameAndShardingValuesMap();
        Collection<Long> userId = columnNameAndShardingValuesMap.get(COLUMN1);
        Collection<Long> roleId = columnNameAndShardingValuesMap.get(COLUMN2);
        if (Optional.ofNullable(userId).isPresent() && Optional.ofNullable(roleId).isPresent()) {
            Long user = userId.stream().findFirst().orElse(0L);
            Long role = roleId.stream().findFirst().orElse(0L);
            Set<String> set = new HashSet<>();
            long i = (user + role) % collection.size();
            collection.forEach(tableName -> {
                if (tableName.contains(String.valueOf(i))) {
                    set.add(tableName);
                }
            });
            return set;
        }
        //如果不是一起的则所有表都查
        return collection;
    }

    @Override
    public String getType() {
        return "COMPLEX_TABLE";
    }
    @Override
    public void init(Properties properties) {
        this.props = properties;
    }
}
